package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.RandomNumberUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.webSocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 提交订单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional //事务一致性
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //处理业务异常情况（地址簿为空、购物车数据为空）
        //查地址数据
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        AddressBook addressBook = addressBookMapper.getById(addressBookId);
        if (addressBook == null) {
            //抛出业务异常
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //查询当前用户的购物车
        //用户id
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> cart = shoppingCartMapper.getByUserId(userId);
        if (cart == null || cart.size() == 0) {
            //抛出业务异常
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //查出用户数据
        User user = userMapper.getById(userId);
        //生成订单号
        String orderNumber = RandomNumberUtil.generateOrderNumber();
        //插表数据
        Orders orders = Orders.builder()
                .number(orderNumber)//可以用时间戳 String.valueOf(System.currentTimeMillis()
                .status(Orders.PENDING_PAYMENT)
                .userId(userId)
                .orderTime(LocalDateTime.now())
                .payStatus(Orders.UN_PAID)
                .phone(addressBook.getPhone())
                .address(addressBook.getDetail())
                .userName(user.getName())
                .consignee(addressBook.getConsignee())
                .build();
        //属性拷贝
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orderMapper.insert(orders);
        //orders表  已全部赋值
        // number(Random生成), status（订单状态 未付款状态）, user_id（由程序获取）,  order_time（当前时间）,
        // checkout_time（尚未结账 null）, pay_status(提交订单 此时还是未支付),
        // phone（查user表得出）, address（查地址簿）, user_name（查user表）, consignee（收货人）, cancel_reason(null),
        // rejection_reason(null), cancel_time(null),
        // delivery_time(送达时间 尚未送达null)

        //OrdersSubmitDTO
        //amount address_book_id tableware_number tableware_status
        // pay_method delivery_status estimated_delivery_time
        //remark pack_amount

        //order_detail表 name image order_id dish_id setmeal_id dish_flavor number amount 插入多条数据
        //order_id需要插入之后才能得到
        //name image dish_id setmeal_id dish_flavor number amount 查购物车数据 由userId查询
        Long ordersId = orders.getId();
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : cart) {
            OrderDetail orderDetail = new OrderDetail();//订单明细
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(ordersId);//设置当前订单明细关联的订单id
            orderDetailList.add(orderDetail);
        }
        //批量插入，操作更快
        orderDetailMapper.insertBatch(orderDetailList);

        //用户下单成功，清空购物车
        shoppingCartMapper.deleteByUserId(userId);

        return OrderSubmitVO.builder()
                .id(ordersId)
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .orderAmount(ordersSubmitDTO.getAmount())
                .build();
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO getOrderDetailById(Long id) {//id是订单id
        OrderVO orderVO = new OrderVO();
        //order表
        Orders orders = orderMapper.getByOrderId(id);
        //属性拷贝
        BeanUtils.copyProperties(orders, orderVO);
        //order_detail表
        List<OrderDetail> list = orderDetailMapper.getByOrderId(id);
        orderVO.setOrderDetailList(list);
        return orderVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //来单提醒
        //通过webSocket向客户端浏览器推送消息 type orderId content
        Map map = new HashMap<>();
        map.put("type", 1);
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号：" + outTradeNo);

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);

    }

    /**
     * 历史订单分页查询
     *
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult pageQuery4User(Integer page, Integer pageSize, Integer status) {
        //当执行多张表的插入的时候同时插入 @Transactional
        //设置分页参数
        PageHelper.startPage(page, pageSize);

        //分页条件查询
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);
        //查orders
        Page<Orders> ordersPage = orderMapper.pageQuery(ordersPageQueryDTO);

        //返回的需要OrderVO
        List<OrderVO> list = new ArrayList<>();
        //查询出订单明细，封装进OrderVO
        for (Orders orders : ordersPage) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            //查询订单明细
            List<OrderDetail> detailList = orderDetailMapper.getByOrderId(orders.getId());
            orderVO.setOrderDetailList(detailList);
            list.add(orderVO);
        }

        return new PageResult(ordersPage.getTotal(), list);
    }

    /**
     * 取消订单
     *
     * @param id
     */
    @Override
    public void cancel4User(Long id) throws Exception {

        Orders orders = orderMapper.getByOrderId(id);
        //校验订单是否存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (orders.getStatus().equals(Orders.TO_BE_CONFIRMED) || orders.getStatus().equals(Orders.PENDING_PAYMENT)) {
            //在待付款、待接单状态下，可以取消，其他清情况需要联系商家
            orders.setCancelTime(LocalDateTime.now());
            orders.setStatus(Orders.CANCELLED);


            // 订单处于待接单状态下取消，需要进行退款
            if (orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
                //调用微信支付退款接口
                weChatPayUtil.refund(
                        orders.getNumber(), //商户订单号
                        orders.getNumber(), //商户退款单号
                        new BigDecimal(0.01),//退款金额，单位 元
                        new BigDecimal(0.01));//原订单金额

                //支付状态修改为 退款
                orders.setPayStatus(Orders.REFUND);
            }

            // 更新订单状态、取消原因、取消时间
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelReason("用户取消");
            orders.setCancelTime(LocalDateTime.now());
            orderMapper.update(orders);
        } else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {
        //再来一单就是把当前订单的数据再加载到购物车当中
        //先查询当前的订单
        //操作的表  order_detail shoppingCart表
        List<OrderDetail> detailList = orderDetailMapper.getByOrderId(id);
        List<ShoppingCart> shoppingCartList = new ArrayList<>();
        //批量插入shoppingCart
        for (OrderDetail orderDetail : detailList) {
            ShoppingCart shoppingCart = ShoppingCart.builder()
                    .image(orderDetail.getImage())
                    .amount(orderDetail.getAmount())
                    .name(orderDetail.getName())
                    .dishFlavor(orderDetail.getDishFlavor())
                    .dishId(orderDetail.getDishId())
                    .createTime(LocalDateTime.now())
                    .setmealId(orderDetail.getSetmealId())
                    .userId(BaseContext.getCurrentId())
                    .number(orderDetail.getNumber())
                    .build();
            shoppingCartList.add(shoppingCart);
        }
        shoppingCartMapper.insertBatch(shoppingCartList);


    }

    /**
     * 分页查询订单 管理端
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery4Admin(OrdersPageQueryDTO ordersPageQueryDTO) {
        //orders order_detail
        //ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());--因为这里是管理端操作，BaseContext.getCurrentId()是
        //是员工的id 也就是1
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
        List<OrderVO> list = new ArrayList<>();
        for (Orders orders : page) {
            StringBuilder sb = new StringBuilder();
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            Long ordersId = orders.getId();
            List<OrderDetail> detailList = orderDetailMapper.getByOrderId(ordersId);
            for (OrderDetail orderDetail : detailList) {
                String name = orderDetail.getName();
                Integer number = orderDetail.getNumber();
                sb.append(name).append("*").append(number).append(";");
            }
            orderVO.setOrderDishes(sb.toString());
            list.add(orderVO);
        }

        return new PageResult(page.getTotal(), list);
    }

    /**
     * 查询各个状态订单的数量
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        //OrderStatisticsVO toBeConfirmed:待接单数量 confirmed：待派送数量 deliveryInProgress：派送中的数量
        List<Orders> ordersList = orderMapper.selectAll();

        int confirmed = 0, ToBeConfirmed = 0, deliveryInProgress = 0;
        for (Orders orders : ordersList) {
            if (orders.getStatus().equals(Orders.CONFIRMED)) {
                confirmed++;
            }
            if (orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
                deliveryInProgress++;
            }
            if (orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
                ToBeConfirmed++;
            }
        }
        return OrderStatisticsVO.builder()
                .confirmed(confirmed)
                .toBeConfirmed(ToBeConfirmed)
                .deliveryInProgress(deliveryInProgress).build();
    }

    /**
     * 接单
     *
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        //接单的逻辑
        //修改status
        Long ordersId = ordersConfirmDTO.getId();
        Orders orders = orderMapper.getByOrderId(ordersId);
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     * @throws Exception
     */
    @Override
    public void reject(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        //拒单的逻辑：1、修改状态
        //2、只有订单处于”待接单“才能执行拒单
        //3、如果用户已经完成了支付，需要退款
        Long orderId = ordersRejectionDTO.getId();
        Orders orders = orderMapper.getByOrderId(orderId);
        Integer status = orders.getStatus();
        //判断当前订单状态
        if (status.equals(Orders.TO_BE_CONFIRMED)) {
            //待接单

            if (orders.getPayStatus().equals(Orders.PAID)) {
                //用户已经支付需要退款
                String refund = weChatPayUtil.refund(
                        orders.getNumber(),
                        orders.getNumber(),
                        new BigDecimal(0.01),
                        new BigDecimal(0.01)
                );
            }
            //设置相关参数
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelTime(LocalDateTime.now());
            orders.setCancelReason(ordersRejectionDTO.getRejectionReason());
            orderMapper.update(orders);
        } else {
            //其他状态不可拒单
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
    }

    /**
     * 用户端取消订单
     *
     * @param ordersCancelDTO
     * @throws Exception
     */
    @Override
    public void cancel4Admin(OrdersCancelDTO ordersCancelDTO) throws Exception {
        //管理端取消订单
        //修改status 为已取消
        //指定原因
        //如果用户已经完成了支付需要退款
        Long orderId = ordersCancelDTO.getId();
        String cancelReason = ordersCancelDTO.getCancelReason();

        Orders orders = orderMapper.getByOrderId(orderId);
        if (orders != null) {
            orders.setStatus(Orders.CANCELLED);
            //指定原因
            orders.setCancelReason(cancelReason);
            //指定取消时间
            orders.setCancelTime(LocalDateTime.now());
            if (orders.getPayStatus().equals(Orders.PAID)) {
                String refund = weChatPayUtil.refund(
                        orders.getNumber(),
                        orders.getNumber(),
                        new BigDecimal(0.01),
                        new BigDecimal(0.01)
                );
            }
            //更新
            orderMapper.update(orders);

        }
    }

    /**
     * 派送订单
     *
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orders = orderMapper.getByOrderId(id);
        Integer status = orders.getStatus();
        if (!status.equals(Orders.CONFIRMED)) {

            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        } else {
            //待派送才能派送订单
            orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
            orderMapper.update(orders);
        }
    }

    /**
     * 完成订单
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        //业务逻辑
        //1、完成订单其实就是将订单状态修改为“已完成”
        //2、只有状态为"派送中"中的订单可以执行完成操作
        Orders orders = orderMapper.getByOrderId(id);
        Integer status = orders.getStatus();
        if (!status.equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.COMPLETED);
        orderMapper.update(orders);
    }

    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.getByOrderId(id);

        //校验订单是否存在
        if(orders==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        Map map=new HashMap();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号："+orders.getNumber());
        String json = JSONObject.toJSONString(map);
        //通过webSocket向客户端浏览器发送消息
        webSocketServer.sendToAllClient(json);
    }
}
